package cn.com.nes.site.modules.sale;

import cn.com.nes.common.exception.BusinessException;
import cn.com.nes.common.exception.IllegalBusinessException;
import cn.com.nes.mybatis.agent.crm.entity.Customer;
import cn.com.nes.mybatis.agent.crm.entity.Opportunity;
import cn.com.nes.mybatis.agent.crm.entity.OpportunityDeviceModel;
import cn.com.nes.mybatis.agent.project.entity.ProjectCustomerRelationship;
import cn.com.nes.site.entity.dto.product.GGoodsDTO;
import cn.com.nes.site.modules.sale.dto.EndUserSaleDetailDTO;
import cn.com.nes.site.modules.sale.dto.SaleDetailDTO;
import cn.com.nes.site.modules.sale.enums.SaleTypeEnum;
import cn.com.nes.site.service.crm.customer.bo.CustomerBO;
import cn.com.nes.site.service.crm.customer.bo.GetCustomerDetailBO;
import cn.com.nes.site.service.crm.customer.dto.CustomerDetailDTO;
import cn.com.nes.site.service.crm.opportunity.OpportunityDeviceModelService;
import cn.com.nes.site.service.crm.opportunity.bo.OpportunityBO;
import cn.com.nes.site.service.crm.opportunity.dto.OpportunityDetailDTO;
import cn.com.nes.site.service.crm.opportunity.dto.OpportunityInfoDto;
import cn.com.nes.site.service.crm.order.bo.QuerySaleOrderDetailBO;
import cn.com.nes.site.service.crm.order.bo.SaleDetailBO;
import cn.com.nes.site.service.crm.order.bo.SaleMasterBO;
import cn.com.nes.site.service.crm.order.bo.SaleOrderBO;
import cn.com.nes.site.service.crm.order.dto.SaleOrderDetailDTO;
import cn.com.nes.site.service.crm.order.dto.SalePriceDetailDTO;
import cn.com.nes.site.service.crm.order.dto.SalePriceMasterDTO;
import cn.com.nes.site.service.project.ProjectCustomerRelationshipService;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 政府终端客户销售业务逻辑层实现
 */
@Slf4j
@Service
public class EndUserSaleHandle extends SaleHandle {

    @Resource
    private ProjectCustomerRelationshipService projectCustomerRelationshipService;

    @Resource
    private OpportunityDeviceModelService opportunityDeviceModelService;

    @Override
    public SaleTypeEnum getSaleTypeEnum() {
        return SaleTypeEnum.GOVERNMENT_PERSONAL_SALES;
    }

    @Override
    protected void preHandleForCustomer(CustomerBO customerBO) throws Exception {
        log.debug("EndUserSaleHandle preHandleForCustomer...");
        validateDuplicateCustomer(customerBO);
    }

    private void validateDuplicateCustomer(CustomerBO customerBO) throws Exception {
        log.debug("EndUserSaleHandle validateDuplicateCustomer...");
        Customer customer = crmCustomerService.getCustomerByIdCardNumber(customerBO.getOperateUserCompanyId(), customerBO.getIdCardNumber());
        if (ObjectUtil.isNotNull(customer)) {
            log.debug("EndUserSaleHandle validateDuplicateCustomer 设置客户UUID...");
            customerBO.setUuid(customer.getUuid());
            customerBO.setAddCustomer(Boolean.FALSE);
        }
    }

    @Override
    protected void preHandleForOpportunity(OpportunityBO opptunityBO) throws Exception {
        log.debug("EndUserSaleHandle preHandleForOpptunity...");
        validateOpportunityExist(opptunityBO);
    }

    private void validateOpportunityExist(OpportunityBO opptunityBO) throws Exception {
        ProjectCustomerRelationship  relationship = projectCustomerRelationshipService.getOtherRelationship(opptunityBO.getCustomerUuid(), opptunityBO.getRelateOpportunityUuid());
        if (ObjectUtil.isNotNull(relationship)) {
            opptunityBO.setUuid(relationship.getBusinessId());
            opptunityBO.setAddOpportunity(Boolean.FALSE);
            return;
        }
        Opportunity opportunity = opportunityBusiness.getOpportunityByName(opptunityBO.getCustomerUuid(), opptunityBO.getOpportunityName());
        if (ObjectUtil.isNotNull(opportunity)) {
            opptunityBO.setUuid(opportunity.getUuid());
            opptunityBO.setAddOpportunity(Boolean.FALSE);
        }
    }

    @Override
    protected void postHandleForOpportunity(Opportunity opportunity, OpportunityBO opptunityBO) throws Exception {
        log.debug("EndUserSaleHandle relateGovernmentPublicOpportunity...");
    }



    @Override
    protected void preHandleForSaleOrder(SaleOrderBO saleOrderBO) throws Exception {
        if (StrUtil.isNotEmpty(saleOrderBO.getRelateOpportunityUuid())) {
            // 校验设备型号
            List<OpportunityDeviceModel> deviceModels = opportunityDeviceModelService.getDeviceModels(saleOrderBO.getRelateOpportunityUuid());
            if (CollUtil.isEmpty(deviceModels)) {
                throw new IllegalBusinessException("当前的政府公共商务项目未设置设备型号范围，此商务项目不能关联到该项目！");
            }
            List<String> deviceModelList = deviceModels.stream()
                    .map(OpportunityDeviceModel::getDeviceModel)
                    .collect(Collectors.toList());
            saleOrderBO.setAllowDeviceModles(deviceModelList);
        }

        super.preHandleForSaleOrder(saleOrderBO);

        log.debug("EndUserSaleHandle preHandleForSaleOrder...");

        BigDecimal orderTotalPrice = BigDecimal.ZERO;
        BigDecimal orderOtherCostPrice = BigDecimal.ZERO;
        for (SaleMasterBO saleMaster : saleOrderBO.getSaleMasters()) {
            BigDecimal masterTotalPrice = BigDecimal.ZERO;
            for (SaleDetailBO saleDetail : saleMaster.getSaleDetails()) {
                if (CollUtil.isNotEmpty(saleOrderBO.getAllowDeviceModles()) && !saleOrderBO.getAllowDeviceModles().contains(saleDetail.getEquipmentId())) {
                    throw new BusinessException("设备型号不符合项目设置的型号范围！");
                }
                String equipmentId = saleDetail.getEquipmentId();
                GGoodsDTO goodsDTO = gGoodsService.getGoodsDetailBySblx(equipmentId);
                saleDetail.setEquipmentModel(goodsDTO.getGoodsCode());
                saleDetail.setEquipmentName(goodsDTO.getGoodsName());
                saleDetail.setBrandId(String.valueOf(goodsDTO.getBrandId()));
                saleDetail.setUnit(Integer.valueOf(goodsDTO.getUnit()));
                saleDetail.setPrice(goodsDTO.getPrice());
                saleDetail.setTotalPrice(goodsDTO.getPrice());
                saleDetail.setCostPrice(goodsDTO.getPrice());
                saleDetail.setTotalCostPrice(goodsDTO.getPrice());
                saleDetail.setGuidePrice(goodsDTO.getPrice());
                masterTotalPrice = masterTotalPrice.add(goodsDTO.getPrice());
            }
            if (ObjectUtil.isNull(saleMaster.getTotalOffer())) {
                saleMaster.setTotalOffer(masterTotalPrice);
            }
            if (ObjectUtil.isNull(saleMaster.getTotalPrice())) {
                saleMaster.setTotalPrice(masterTotalPrice);
            }
            orderTotalPrice = orderTotalPrice.add(saleMaster.getTotalPrice());
            orderOtherCostPrice = orderOtherCostPrice.add(saleMaster.getOtherCostPrice());
        }
        if (ObjectUtil.isNull(saleOrderBO.getTotalPrice())) {
            saleOrderBO.setTotalPrice(orderTotalPrice);
        }
        if (ObjectUtil.isNull(saleOrderBO.getOtherCostPrice())) {
            saleOrderBO.setOtherCostPrice(orderOtherCostPrice);
        }
        if (ObjectUtil.isNull(saleOrderBO.getTotalOffer())) {
            saleOrderBO.setTotalOffer(orderTotalPrice);
        }
    }

    /**
     * 查询政府终端客户的销售详情
     * saleDetailBO 参数有同名类,这里使用全路径声明
     * 政府终端客户的销售详情 - 客户详情、商机详情、销售详情
     */
    @Override
    public SaleDetailDTO getSaleDetail(cn.com.nes.site.modules.sale.bo.SaleDetailBO saleDetailBO) throws Exception {
        // 查询商机详情
        OpportunityDetailDTO opportunityDetail = this.getOpportunityDetail(saleDetailBO);
        if (ObjectUtil.isNull(opportunityDetail)) {
            return new SaleDetailDTO();
        }

        // 查询客户详情
        CustomerDetailDTO customerDetail = new CustomerDetailDTO();
        // 如果商机详情返回了客户id,就查询客户详情
        if (ObjectUtil.isNotNull(opportunityDetail.getOpportunityInfo()) && StrUtil.isNotBlank(opportunityDetail.getOpportunityInfo().getCustomerId())) {
            saleDetailBO.setCustomerUuid(opportunityDetail.getOpportunityInfo().getCustomerId());
            customerDetail = this.getCustomerDetail(saleDetailBO);
        }

        // 查询销售订单详情
        SaleOrderDetailDTO saleOrderDetail = this.getSaleOrderDetail(saleDetailBO);

        // 组装返回值
        EndUserSaleDetailDTO saleDetailDTO = new EndUserSaleDetailDTO();
        saleDetailDTO.setCustomerDetail(customerDetail);
        saleDetailDTO.setOpportunityDetail(opportunityDetail);
        saleDetailDTO.setSaleOrderDetail(saleOrderDetail);
        // 后置处理
        return this.postHandle(saleDetailDTO);
    }

    /**
     * 查询客户详情 - 政府终端客户是一个商机只有一个客户
     */
    @Override
    protected CustomerDetailDTO getCustomerDetail(cn.com.nes.site.modules.sale.bo.SaleDetailBO saleDetailBO) throws Exception {
        GetCustomerDetailBO getCustomerDetailBO = saleDetailBO.copyOperateInfo(GetCustomerDetailBO.class);
        getCustomerDetailBO.setCustomerId(saleDetailBO.getCustomerUuid());

        return crmCustomerService.getCustomerDetail(getCustomerDetailBO);
    }

    /**
     * 查询商机详情
     */
    @Override
    protected OpportunityDetailDTO getOpportunityDetail(cn.com.nes.site.modules.sale.bo.SaleDetailBO saleDetailBO) throws Exception {
        return super.getOpportunityDetail(saleDetailBO);
    }

    /**
     * 查询销售订单详情
     */
    @Override
    protected SaleOrderDetailDTO getSaleOrderDetail(cn.com.nes.site.modules.sale.bo.SaleDetailBO saleDetailBO) {
        QuerySaleOrderDetailBO querySaleOrderDetailBO = saleDetailBO.copyOperateInfo(QuerySaleOrderDetailBO.class);
        return saleOrderInfoService.getSaleOrderDetail(querySaleOrderDetailBO);
    }

    /**
     * 处理返回值
     */
    @Override
    protected SaleDetailDTO postHandle(SaleDetailDTO saleDetailDTO) {
        if (!(saleDetailDTO instanceof EndUserSaleDetailDTO)) {
            return saleDetailDTO;
        }
        // 准备返回值
        EndUserSaleDetailDTO endUserSaleDetailDTO = (EndUserSaleDetailDTO) saleDetailDTO;
        // 取出待处理的数据
        CustomerDetailDTO customerDetail = endUserSaleDetailDTO.getCustomerDetail();
        OpportunityDetailDTO opportunityDetail = endUserSaleDetailDTO.getOpportunityDetail();
        SaleOrderDetailDTO saleOrderDetail = endUserSaleDetailDTO.getSaleOrderDetail();
        OpportunityInfoDto opportunityInfo = opportunityDetail.getOpportunityInfo();
        // 开始单独给字段赋值
        endUserSaleDetailDTO.setAddress(customerDetail.getCustomerInfo().getAddress());
        endUserSaleDetailDTO.setAreaCode(customerDetail.getCustomerInfo().getXzqhdm());
        endUserSaleDetailDTO.setBuildArea(customerDetail.getCustomerHouseList().get(0).getFloorSpace()); // 建筑面积
        endUserSaleDetailDTO.setBuildingHeight(opportunityInfo.getBuildingHeight());
        endUserSaleDetailDTO.setBuildingStructure(opportunityInfo.getBuildingStructure());
        endUserSaleDetailDTO.setBuildingType(customerDetail.getCustomerHouseList().get(0).getHouseType());
        endUserSaleDetailDTO.setCommonHeatingArea(opportunityInfo.getCommonHeatingArea());
        endUserSaleDetailDTO.setCustomerCode(customerDetail.getCustomerInfo().getCustomerCode()); // 客户编号
        endUserSaleDetailDTO.setCustomerName(customerDetail.getCustomerInfo().getCustomerName());
        endUserSaleDetailDTO.setDesignCompany(opportunityInfo.getDesignCompany());
        endUserSaleDetailDTO.setDesignDirection(opportunityInfo.getDesignHeatingLoad());
        endUserSaleDetailDTO.setEndState(opportunityInfo.getEndState());
        endUserSaleDetailDTO.setEnergyType(opportunityInfo.getEnergyType());
        endUserSaleDetailDTO.setHeatingArea(opportunityInfo.getHeatingArea());
        endUserSaleDetailDTO.setHeatingEnd(opportunityInfo.getHeatingEnd());
        endUserSaleDetailDTO.setHeatingMode(opportunityInfo.getHeatingMode());
        endUserSaleDetailDTO.setHouseArea(customerDetail.getCustomerHouseList().get(0).getFloorSpace());
        endUserSaleDetailDTO.setHouseDirection(opportunityInfo.getHouseDirection());
        endUserSaleDetailDTO.setHouseNumber(opportunityInfo.getHouseNumber());
        endUserSaleDetailDTO.setHousePurpose(opportunityInfo.getHousePerpose());
        endUserSaleDetailDTO.setIdCardNumber(customerDetail.getCustomerInfo().getIdCardNumber());
        endUserSaleDetailDTO.setInstallPosition(opportunityInfo.getInstallPosition());
        endUserSaleDetailDTO.setInstallPhotovoltaic(ObjectUtil.isNull(opportunityInfo.getInstallPhotovoltaic()) ? "0" : opportunityInfo.getInstallPhotovoltaic() ? "1" : "0");
        endUserSaleDetailDTO.setLocalHouseHold(opportunityInfo.getHouseholdRegistration());
        endUserSaleDetailDTO.setOpportunityUuid(opportunityInfo.getUuid());
        endUserSaleDetailDTO.setMeterNumber(opportunityInfo.getMeterNumber());
        endUserSaleDetailDTO.setNatureEnergyType(customerDetail.getCustomerInfo().getEnergyUsePropertyCode());
        endUserSaleDetailDTO.setNewlyDeclaredArea(opportunityInfo.getNewlyDeclaredArea());
        endUserSaleDetailDTO.setOriginalDeclaredArea(opportunityInfo.getOriginalDeclaredArea());
        endUserSaleDetailDTO.setOuterWallKeepWarm(opportunityInfo.getOuterWallKeepWarm());
        endUserSaleDetailDTO.setOuterWallThickness(opportunityInfo.getOuterWallThickness());
        endUserSaleDetailDTO.setPaperCode(opportunityInfo.getDrawingNo());
        endUserSaleDetailDTO.setPhone(customerDetail.getCustomerInfo().getPhone());
        endUserSaleDetailDTO.setPlanYear(opportunityInfo.getPlanYear());
        endUserSaleDetailDTO.setRoomCount(opportunityInfo.getRoomCount());
        endUserSaleDetailDTO.setWindowType(opportunityInfo.getWindowType());
        endUserSaleDetailDTO.setDbhhwbh(opportunityInfo.getDbhhwbh());
        endUserSaleDetailDTO.setApplicationType(opportunityInfo.getApplicationType());
        endUserSaleDetailDTO.setXzqhdm(opportunityInfo.getXzqhdm());
        endUserSaleDetailDTO.setIsVillagers("0");
        endUserSaleDetailDTO.setCustomerNameNow(customerDetail.getCustomerInfo().getCustomerNameNow());
        endUserSaleDetailDTO.setIdCardNumberNow(customerDetail.getCustomerInfo().getIdCardNumberNow());
        endUserSaleDetailDTO.setPhoneNow(customerDetail.getCustomerInfo().getPhoneNow());
        endUserSaleDetailDTO.setIsHouseholder(customerDetail.getCustomerInfo().getIsHouseholder());
        endUserSaleDetailDTO.setCustomerStaffId(customerDetail.getCustomerInfo().getCustomerStaffId());
        //新增客户的身份证和户口本等文件
        endUserSaleDetailDTO.setFileList(saleDetailDTO.getCustomerDetail().getFileList());
        if (StrUtil.isNotBlank(customerDetail.getCustomerInfo().getVillagers())) {
            endUserSaleDetailDTO.setIsVillagers("true".equals(customerDetail.getCustomerInfo().getVillagers()) ? "1" : "0");
        }
        endUserSaleDetailDTO.setDesignDrawings(opportunityDetail.getPicMap().get("designDrawings"));
        endUserSaleDetailDTO.setPlaneGraphs(opportunityDetail.getPicMap().get("planeGraphs"));
        endUserSaleDetailDTO.setSbgzcns(opportunityDetail.getPicMap().get("sbgzcns"));
        // 处理系统单列表
        endUserSaleDetailDTO.setSaleMasters(saleOrderDetail.getSalePriceMasterDTOList());
//        endUserSaleDetailDTO.setDeviceList(Collections.emptyList());
//        endUserSaleDetailDTO.setSelectDeviceList(Collections.emptyList());
        if(CollUtil.isNotEmpty(endUserSaleDetailDTO.getSaleMasters())) {
            for (SalePriceMasterDTO saleMaster : endUserSaleDetailDTO.getSaleMasters()) {
                saleMaster.setChildList(new ArrayList<>());
                for (SalePriceDetailDTO salePriceDetailDTO : saleOrderDetail.getSalePriceDetailDTOList()) {
                    if (salePriceDetailDTO.getPriceMasterId().equals(saleMaster.getId())) {
                        saleMaster.getChildList().add(salePriceDetailDTO);
                    }
                }
            }
        }

        // 去除冗余字段
        endUserSaleDetailDTO.setCustomerDetail(null);
        endUserSaleDetailDTO.setOpportunityDetail(null);
        endUserSaleDetailDTO.setSaleOrderDetail(null);
        return endUserSaleDetailDTO;
    }
}
